package cn.bellychang.recursion.liuxin;

/**
 * @author: bellychang
 * @date: 2020/2/12
 */
public class Factorial {

    public int factorial(int num) {
        if (num <= 0) {
            throw new IllegalArgumentException();
        }
        if (num == 1) {
            return 1;
        } else {
            return factorial(num - 1) * num;
        }
    }

    /**
     * 当递归调用是函数体中最后执行的语句并且它的返回值不属于表达式的一部分时，这个递归就是尾递归
     *
     * @param num
     * @return
     */
    public int factorialWithTailRecursion(int num, int result) {
        if (num <= 0) {
            throw new IllegalArgumentException();
        }
        if (num == 1) {
            return result;
        } else {
            return factorialWithTailRecursion(num - 1, num * result);
        }
    }
}
